package com.bubaiwantong.algorithms2.select;

/**
 * All rights Reserved, Designed By www.tom.com
 *
 * @Author 徐望成
 * @Date 2023/11/7 12:06
 * @PackageName:com.bubaiwantong.algorithms2.select
 * @ClassName: HeapSort
 * @Description: TODO
 * @Copyright: 2019 www.tomonline-inc.com Inc. All rights reserved.
 * 注意：本内容仅限于TOM集团内部传阅，禁止外泄以及用于其他的商业目
 * @Version 1.0
 */
public class HeapSort {
    public static void main(String[] args) {
        HeapSort heapSort = new HeapSort();
//        int[] arr = new int[]{9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
        int[] arr = new int[]{9, 8, 7, 6, 0, 5, 4, 3, 2, 1};
        heapSort.printArr(arr);
        heapSort.sort(arr);
        heapSort.printArr(arr);
    }

    /**
     * 大根堆排序
     *
     * @param arr
     */
    public void sort(int arr[]) {
        for (int i = arr.length / 2; i > 0; i--) {
            adjust(arr, i, arr.length);
        }

        for (int i = arr.length - 1; i > 0; i--) {
            adjust(arr, 0, i);
            swap(arr, 0, i);
        }

    }

    /**
     * 调整大根堆
     *
     * @param arr
     * @param i
     * @param length
     */
    public void adjust(int arr[], int i, int length) {
        int temp = arr[i];
        for (int k = 2 * i + 1; k < length; k = 2 * k + 1) {
            if (k + 1 < length && arr[k] < arr[k + 1]) {
                k += 1;
            }
            if (temp > arr[k]) {
                break;
            } else {
                arr[i] = arr[k];
                i = k;
            }
        }
        arr[i] = temp;
    }

    public void printArr(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    public void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}
